package com.reader.core.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liujianqing
 * @date 2018/10/28
 */public class JsonUtils {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    private static ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static ObjectMapper getMapper() {
        return MAPPER;
    }

    /**
     * 序列化成json.
     * 
     * @param object 对象
     * @return json String
     */
    public static String toString(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            logger.error("JsonUtils#toString : toString error", e);
        }
        return "";
    }

    /**
     * 反序列化成对象.
     * 
     * @param value　jsonStr
     * @param valueType Type Class
     * @param <T> Type
     * @return T Object
     */
    public static <T> T toObject(String value, Class<T> valueType) {
        try {
            return MAPPER.readValue(value, valueType);
        } catch (Exception e) {
            logger.error("JsonUtils#toObject : toObject error value->{} T->{}", value,
                    valueType.getName(), e);
        }
        return null;
    }
}
